package com.ryskoo.controller.order;

import com.ryskoo.catering.ordermain.domain.OrderMainPO;
import com.ryskoo.catering.ordermain.service.IOrderMainService;
import com.ryskoo.common.hclconstant.EatTypeEnum;
import com.ryskoo.common.hclconstant.OrderStateEnum;
import com.ryskoo.common.hclconstant.PayStateEnum;
import com.ryskoo.common.hclconstant.PayTypeEnum;
import com.ryskoo.customer.vendormanager.domain.VendorManagerPO;
import com.ryskoo.framework.core.bean.*;
import com.ryskoo.framework.core.controller.BasicHandler;
import com.ryskoo.framework.core.utils.LoginUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * HCL订单管理
 * @author BeHappy
 */
@Controller
@RequestMapping("/vendor/ordermain")
public class OrderMainController extends BasicHandler<OrderMainPO> {
    private static final Logger logger = LogManager.getLogger(OrderMainController.class);

    private static final String TEMPLATE_PATH = "system/ordermain";

    private static final String MODULE_NAME = "OrderMain";
    /**
     * 基类构造方法.
     */
    public OrderMainController() {
        super(TEMPLATE_PATH, MODULE_NAME);
    }

    private IOrderMainService orderMainService;

    /**
     * 消费者注入
     *
     * @param orderMainService 消费者基类
     */
    @Autowired
    protected void setService(IOrderMainService orderMainService) {
        this.orderMainService = orderMainService;
        super.setService(orderMainService);
    }

    @Override
    protected void buildListPageData(Model model, HttpServletRequest request) {
        List<EnumConvertParam> stateList = new ArrayList<>();
        for (OrderStateEnum ose : OrderStateEnum.values()) {
            EnumConvertParam param = new EnumConvertParam();
            param.setValue(ose.getValue());
            param.setName(ose.getName());
            stateList.add(param);
        }
        List<EnumConvertParam> payStateList = new ArrayList<>();
        for (PayStateEnum pse : PayStateEnum.values()) {
            EnumConvertParam param = new EnumConvertParam();
            param.setValue(pse.getValue());
            param.setName(pse.getName());
            payStateList.add(param);
        }
        List<EnumConvertParam> eatTypeList = new ArrayList<>();
        for (EatTypeEnum ete : EatTypeEnum.values()) {
            if(ete.getValue() == EatTypeEnum.YUYUE.getValue()){
                continue;
            }
            EnumConvertParam param = new EnumConvertParam();
            param.setValue(ete.getValue());
            param.setName(ete.getName());
            eatTypeList.add(param);
        }
        List<EnumConvertParam> payTypeList = new ArrayList<>();
        for (PayTypeEnum pte : PayTypeEnum.values()) {
            EnumConvertParam param = new EnumConvertParam();
            param.setValue(pte.getValue());
            param.setName(pte.getName());
            payTypeList.add(param);
        }
        model.addAttribute("stateList", stateList);
        model.addAttribute("payStateList", payStateList);
        model.addAttribute("eatTypeList", eatTypeList);
        model.addAttribute("payTypeList", payTypeList);
    }

    /**
     * 查询列表
     *
     * @param qm 统一查询消息 {@link QueryMessageDTO}
     * @return 统一返回消息 {@link ReturnMessageDTO}&lt;{@link List}&lt;{@link OrderMainPO}&gt;&gt;
     */
    @ResponseBody
    @PostMapping("/list")
    public ReturnMessageDTO<List<OrderMainPO>> list(@RequestBody QueryMessageDTO qm) {
        String vendorUuid = LoginUtil.getLoginVendorUuid();
        ReturnMessageDTO<List<OrderMainPO>> returnMessage = new ReturnMessageDTO<>();
        qm.addCondition("vendorUuid", QueryConditionEnum.EQ.name(), vendorUuid);
        qm.addCondition("orderType", QueryConditionEnum.NE.name(), 0);
        List<OrderMainPO> list = orderMainService.getList4FrontAndPage(qm);
        int count = orderMainService.getCount(qm);
        returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
        returnMessage.setReturnNote("查询成功");
        returnMessage.setReturnMessage(list);
        returnMessage.setPager(new Pager(qm.getPageShow(), qm.getStartNum(), count));
        return returnMessage;
    }


    @Override
    @GetMapping("/toview/{id}")
    public String toView(@PathVariable(value = "id") String id, Model model, HttpServletRequest request) {
        //获取订单系列数据，包括订单信息、订单明细、订单日志等
        //调用来源：后台
        String invokeFrom = "backWeb";
        OrderMainPO dto = orderMainService.getFamily(id, invokeFrom);
        model.addAttribute("order", dto);
        return TEMPLATE_PATH + "/" + MODULE_NAME + "View";
    }

    /**
     * 商家接单
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/receive")
    ReturnMessageDTO receive(@RequestParam(value = "id") String id) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.receive(id, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("商家接单成功");
            returnMessage.setReturnMessage(po);

            //老板接单后，推送给厨师长出菜（异步）
            orderMainService.pushToChief(po.getUuid());
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("商家接单失败");
            logger.error("商家接单失败", e);
        }
        return returnMessage;
    }

    /**
     * 商家完成订单
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/finish")
    ReturnMessageDTO finish(@RequestParam(value = "id") String id) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.finish(id, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("确认完成成功");
            returnMessage.setReturnMessage(po);
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("确认完成失败");
            logger.error("确认完成失败", e);
        }
        return returnMessage;
    }

    /**
     * 订单派送
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delivery")
    ReturnMessageDTO delivery(@RequestParam(value = "id") String id) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.delivery(id, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("订单派送成功");
            returnMessage.setReturnMessage(po);
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("订单派送失败");
            logger.error("订单派送失败", e);
        }
        return returnMessage;
    }

    /**
     * 订单已送达
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/arrived")
    ReturnMessageDTO arrived(@RequestParam(value = "id") String id) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.arrived(id, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("订单送达成功");
            returnMessage.setReturnMessage(po);
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("订单送达失败");
            logger.error("订单送达失败", e);
        }
        return returnMessage;
    }

    /**
     * 收款
     *
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/gathering")
    ReturnMessageDTO gathering(@RequestParam(value = "id") String id, @RequestParam(value = "payMoney") double payMoney) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.gathering(id, payMoney, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("收款成功");
            returnMessage.setReturnMessage(po);
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("收款失败");
            logger.error("收款失败", e);
        }
        return returnMessage;
    }

    /**
     * 商家取消订单
     *
     * @param id
     * @param refundMoney
     * @return
     */
    @ResponseBody
    @PostMapping("/cancel")
    ReturnMessageDTO cancel(@RequestParam(value = "id") String id, @RequestParam(value = "refundMoney", required = false, defaultValue = "0") Double refundMoney) {
        ReturnMessageDTO returnMessage = new ReturnMessageDTO();
        try {
            VendorManagerPO vendorManager = LoginUtil.getLoginUserModel();
            OrderMainPO po = orderMainService.cancelFromVendor(id, refundMoney, vendorManager.getUuid(), vendorManager.getName());
            returnMessage.setReturnCode(ReturnCodeEnum.SUCCESS.getReturnCode());
            returnMessage.setReturnNote("取消成功");
            returnMessage.setReturnMessage(po);
        } catch (Exception e) {
            returnMessage.setReturnCode(ReturnCodeEnum.ERROR.getReturnCode());
            returnMessage.setReturnNote("取消失败");
            logger.error("取消失败", e);
        }
        return returnMessage;
    }

}
